package cn.hwadee.muying.commons.utils.beetl;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.beetl.core.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @ClassName: AuthTag
 * @Description: 权限标签
 * @author lqq
 * @date 2016年5月11日 下午7:32:15
 *
 */
@Service
@Scope("prototype")
public class AuthTag extends Tag{

    @SuppressWarnings("unused")
    private static Logger log = LoggerFactory.getLogger(AuthTag.class);

    /**
     * 权限行为集合
     */
    private static Map<String, Method> actionList = new HashMap<>();


    //初始化权限行为
    static{
        String authTypes="button,a,checkbox,field,tableCol";
        String[] auth_type_list = authTypes.split(",");
        for(String auth_type : auth_type_list){
            try {
                actionList.put(auth_type, AuthTag.class.getMethod(auth_type));
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 标签id
     */
    private String id;
    /**
     * 权限类型
     */
    private String type;

    /**
     * 权限标识
     */
    private String perm;

    /**
     * 按钮文本值
     */
    private String text;
    /**
     * 点击事件
     */
    private String onclick;
    /**
     * name 参数
     */
    private String name;
    /**
     * class 参数
     */
    private String extClass;
    /**
     * 文字图标
     */
    private String iconText;
    /**
     * data-id 参数
     */
    private String dataId;
    /**
     * target 参数
     */
    private String target;
    /**
     * lay-filter 参数
     */
    private String layFilter;
    /**
     * value 参数
     */
    private String value;
    /**
     * checked 参数
     */
    private String checked;


    @SuppressWarnings("unchecked")
    @Override
    public void render() {

        try {

            Map<String, String> param = (Map<String, String>) args[1];

            this.type = param.get("type") == null ? "" : param.get("type");

            this.perm = param.get("perm") == null ? "" : param.get("perm");

            this.text = param.get("text") == null ? "" : param.get("text");

            this.id = param.get("id") == null ? "" : param.get("id");

            this.onclick = param.get("onclick") == null ? "" : param.get("onclick");

            this.name = param.get("name") == null ? "" : param.get("name");

            this.extClass = param.get("extClass") == null ? "" : param.get("extClass");

            this.iconText = param.get("iconText") == null ? "" : param.get("iconText");

            this.dataId = param.get("dataId") == null ? "" : param.get("dataId");

            this.target = param.get("target") == null ? "" : param.get("target");

            this.layFilter = param.get("layFilter") == null ? "" : param.get("layFilter");

            this.value = param.get("value") == null ? "" : param.get("value");

            this.checked = param.get("checked") == null ? "" : param.get("checked");

            //根据权限类型调用相关的方法
            ctx.byteWriter.writeString((String) actionList.get(type).invoke(this));

        } catch (IOException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @Title: button
     * @Description: 查看、编辑、删除按钮
     * @param
     * @return String
     * @throws
     */
    public String button(){
        StringBuilder sb = new StringBuilder();
        if(SecurityUtils.getSubject().isPermitted(perm)){
            text = StringUtils.isBlank(text) ? "" : text;
            sb.append("<button type=\"button\" class=\"layui-btn ").append(extClass).append("\" ")
                    .append("id=\"").append(id).append("\" ")
                    .append("name=\"").append(name).append("\" ")
                    .append("data-id=\"").append(dataId).append("\" ");

            if(!"".equals(onclick)){
                sb.append("onclick=\"").append(onclick).append("\" ");
            }

            sb.append(">");
            if(!"".equals(iconText)) {
                sb.append("<i class=\"layui-icon\">").append(iconText).append("</i>");
            }
            sb.append(text).append("</button>");
        }

        return sb.toString();
    }

    /**
     *
     * @Title: a
     * @Description: 链接按钮
     * @param
     * @return String
     * @throws
     */
    public String a(){
        StringBuilder sb = new StringBuilder();

        if(SecurityUtils.getSubject().isPermitted(perm)){
            text = StringUtils.isBlank(text) ? "" : text;
            sb.append("<a type=\"button\" class=\"layui-btn ").append(extClass).append("\" ")
                    .append("id=\"").append(id).append("\" ")
                    .append("name=\"").append(name).append("\" ")
                    .append("data-id=\"").append(dataId).append("\" ");

            if(!"".equals(onclick)){
                sb.append("onclick=\"").append(onclick).append("\" ");
            }
            if(!"".equals(target)){
                sb.append("target=\"").append(target).append("\" ");
            }

            sb.append(">");
            if(!"".equals(iconText)) {
                sb.append("<i class=\"layui-icon\">").append(iconText).append("</i>");
            }
            sb.append(text).append("</a>");
        }

        return sb.toString();
    }

    /**
     *
     * @Title: checkbox
     * @Description: 复选框
     * @param
     * @return String
     * @throws
     */
    public String checkbox(){
        StringBuilder sb = new StringBuilder();

        if(SecurityUtils.getSubject().isPermitted(perm)){
            text = StringUtils.isBlank(text) ? "" : text;
            sb.append("<input type=\"checkbox\"")
                    .append("lay-filter=\"").append(layFilter).append("\" ")
                    .append("id=\"").append(id).append("\" ")
                    .append("name=\"").append(name).append("\" ")
                    .append("title=\"").append(text).append("\" ")
                    .append("value=\"").append(value).append("\" ")
                    .append("data-id=\"").append(dataId).append("\" ");

            sb.append(checked);
            sb.append(">");

        }
        return sb.toString();
    }



    /**
     * @Title: field
     * @Description: 销售统计字段
     * @return
     */
    public String field() {
        StringBuilder sb = new StringBuilder();
        if (SecurityUtils.getSubject().isPermitted(perm)) {
            text = StringUtils.isBlank(text) ? "" : text;
            sb.append(text);
            if (name.equals("总广告费(美金)")) {
                sb.append("    formatter : function(cellvalue, options, rowdata){\n" +
                        "        var html = '';\n" +
                        "        if(rowdata.id > 0){\n" +
                        "            html = '<input type=\"text\" id=\"totalAdUSD_' + rowdata.id + '\" value=\"' + (cellvalue!=null?cellvalue:'') + '\" class=\"layui-input\" style=\"display: inline-block;width:95%;margin-top: 4px;\">' +\n" +
                        "                    '<input type=\"hidden\" name=\"id\" value=\"' + rowdata.id + '\" />';\n" +
                        "        }else {\n" +
                        "            html = '<input type=\"text\" readonly id=\"totalAdUSD_' + rowdata.id + '\" value=\"' + (cellvalue!=null?cellvalue:'') + '\" class=\"layui-input\" style=\"display: inline-block;width:95%;margin-top: 4px;\">';\n" +
                        "        }\n" +
                        "        return html;\n" +
                        "    }\n" +
                        "},");
            }
            if(name.equals("总营业额(美金)")){
                sb.append(" formatter : function(cellvalue, options, rowdata){\n" +
                        "            var html = '';\n" +
                        "            if(rowdata.id > 0){\n" +
                        "                html = '<input type=\"text\" id=\"totalTurnoverUSD_' + rowdata.id + '\" value=\"' + (cellvalue!=null?cellvalue:'') + '\" class=\"layui-input\" style=\"display: inline-block;width:95%;margin-top: 4px;\">';\n" +
                        "            }else {\n" +
                        "                html = '<input type=\"text\" readonly id=\"totalTurnoverUSD_' + rowdata.id + '\" value=\"' + (cellvalue!=null?cellvalue:'') + '\" class=\"layui-input\" style=\"display: inline-block;width:95%;margin-top: 4px;\">';\n" +
                        "            }\n" +
                        "            return html;\n" +
                        "        }\n" +
                        "    },");
            }
            if(name.equals("额外费用(美金)")){
                sb.append(" {\n" +
                        "        name : \"extraCostUSD\",\n" +
                        "        index : \"extraCostUSD\",\n" +
                        "        width : 120,\n" +
                        "        title:false,\n" +
                        "        editable:true,\n" +
                        "        align : \"left\",\n" +
                        "        formatter : function(cellvalue, options, rowdata){\n" +
                        "            var html = '';\n" +
                        "            if(rowdata.id > 0){\n" +
                        "                html = '<input type=\"text\" id=\"extraCostUSD_' + rowdata.id + '\" value=\"' + (cellvalue!=null?cellvalue:'') + '\" class=\"layui-input\" style=\"display: inline-block;width:95%;margin-top: 4px;\">';\n" +
                        "            }else {\n" +
                        "                html = '<input type=\"text\" readonly id=\"extraCostUSD_' + rowdata.id + '\" value=\"' + (cellvalue!=null?cellvalue:'') + '\" class=\"layui-input\" style=\"display: inline-block;width:95%;margin-top: 4px;\">';\n" +
                        "            }\n" +
                        "            return html;\n" +
                        "        }\n" +
                        "    },");
            }
            if(name.equalsIgnoreCase("crawler")){
                sb.append(",{\n" +
                        "        name : \"enable\",\n" +
                        "        index : \"enable\",\n" +
                        "        sortable : true,\n" +
                        "        width : 100,\n" +
                        "        align : \"center\",\n" +
                        "        formatter : function(cellvalue, options, rowdata){\n" +
                        "            return '<form class=\"layui-form\" style=\"padding-top: 5px\">' +\n" +
                        "                '<input type=\"checkbox\"lay-filter=\"c_enable\" id=\"\" name=\"enable\" title=\"启用\" value=\"'+(cellvalue?'on':'off')+'\" data-id=\"' + rowdata.productId+ '\" '+(cellvalue?'checked':'')+'>' +\n" +
                        "                '</form>';\n" +
                        "        }\n" +
                        "    }");
            }
        }
        return sb.toString();

    }


    /**
     * 表格列头元素
     * @return
     */
    public String tableCol(){
        // "总单量", "总广告费(美金)", "总营业额(美金)", "额外费用(美金)", "总广告费(RMB)",
        // "总营业额(RMB)", "额外费用(RMB)", "广告占比", "总成本", "实际利润", "总回款"

        //表格列头
        StringBuilder sb = new StringBuilder();
        if(SecurityUtils.getSubject().isPermitted(perm)){
            //权限编码
            String[] pcodes={"biz:saleReport:listallorder","biz:saleReport:listADUSD",
                    "biz:saleReport:listtotalTurnoverUSD","biz:saleReport:listextraCostUSD","biz:saleReport:listtotalAdRMB",
                    "biz:saleReport:listtotalTurnoverRMB","biz:saleReport:listextraCostRMB",
                    "biz:saleReport:listratioStr","biz:saleReport:listtotalCost",
                    "biz:saleReport:listactualProfit","biz:saleReport:listtotalProfit"};
            //字段权限名
            String[] pnames={"\"总单量\"", "\"总广告费(美金)\"", "\"总营业额(美金)\"", "" +
                    "\"额外费用(美金)\"", "\"总广告费(RMB)\"", "\"总营业额(RMB)\"", "\"额外费用(RMB)\"", "\"广告占比\"", "\"总成本\"", "\"实际利润\"", "\"总回款\""};
            for(int i=0;i<pcodes.length;i++){
                if(SecurityUtils.getSubject().isPermitted(pcodes[i])||SecurityUtils.getSubject().hasRole("super admin")){
                    sb.append(",").append(pnames[i]).append("");
                }

            }
        }
        return sb.toString();
    }
}